package com.hrw.musicplayer.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.hrw.musicplayer.R;
import com.hrw.musicplayer.adapter.ImageAdapter;
import com.hrw.musicplayer.adapter.MusicAdapter;
import com.hrw.musicplayer.db.DataBaseProvider;
import com.hrw.musicplayer.db.FileTable;
import com.hrw.musicplayer.utils.Constants;
import com.hrw.musicplayer.utils.MediaPlayerUtil;

public class MainActivity extends Activity {

	private static final int MUSIC_LIST_DIALOG = 1;

	private ImageButton stop_btn;

	private ImageButton play_btn;

	private ImageButton prev_btn;

	private ImageButton next_btn;

	private ImageButton play_list_btn;

	private ImageButton back_btn;

	private ImageButton add_music_btn;

	private ImageButton exit_btn;

	private SeekBar seek_bar;

	private AlertDialog music_list_dialog;

	private TextView current_music_name_text;

	private TextView current_time;

	private TextView end_time;

	private ListView play_list_view;

	private Handler seek_bar_handler = new Handler();

	private String selected_music_name;

	private List<String> music_list;

	private MediaPlayerUtil mpu;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main_activity);
		init();
	}
	

	private void init() {
		play_btn = (ImageButton) findViewById(R.id.playBtn);
		play_btn.setOnTouchListener(playListener);
		prev_btn = (ImageButton) findViewById(R.id.prevBtn);
		prev_btn.setOnTouchListener(prevListener);
		next_btn = (ImageButton) findViewById(R.id.nextBtn);
		next_btn.setOnTouchListener(nextListener);
		stop_btn = (ImageButton) findViewById(R.id.stopBtn);
		stop_btn.setOnTouchListener(stopListener);
		play_list_btn = (ImageButton) findViewById(R.id.playListBtn);
		play_list_btn.setOnTouchListener(playListListener);

		exit_btn = (ImageButton) findViewById(R.id.exitBtn);
		exit_btn.setOnTouchListener(exitListener);
		current_music_name_text = (TextView) findViewById(R.id.current_music_name);
		current_music_name_text.setText("N/A");
		current_time = (TextView) findViewById(R.id.current_time_text);
		end_time = (TextView) findViewById(R.id.end_time_Text);

		Gallery g = (Gallery) findViewById(R.id.gallery);
		g.setAdapter(new ImageAdapter(this));
		g.setSelection(0);

		seek_bar = (SeekBar) findViewById(R.id.seekbar);
		seek_bar.setOnSeekBarChangeListener(seekbarListener);
		mpu = MediaPlayerUtil.getInstance(onCompeletionListener);
	}

	OnCompletionListener onCompeletionListener = new OnCompletionListener() {
		@Override
		public void onCompletion(MediaPlayer mp) {
			seek_bar_handler.removeCallbacks(refresh);
			stop();
			play_btn.setImageResource(R.drawable.play);
		}
	};

	OnSeekBarChangeListener seekbarListener = new OnSeekBarChangeListener() {
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			if (fromUser) {
				seek_bar_handler.removeCallbacks(refresh);
				current_time.setText(getFileTime(progress));
			}

		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {

		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			mpu.seekTo(seekBar.getProgress());
			seek_bar_handler.postDelayed(refresh, 1000);
		}
	};

	OnTouchListener exitListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				exit_btn.setImageResource(R.drawable.whitepress);

			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				exit_btn.setImageResource(R.drawable.white);
				finish();
				android.os.Process.killProcess(android.os.Process.myPid());
			}

			return false;

		}

	};

	OnTouchListener playListListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				play_list_btn.setImageResource(R.drawable.itunespress);
				showDialog(MUSIC_LIST_DIALOG);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				play_list_btn.setImageResource(R.drawable.itunes2);
			}
			return false;
		}

	};

	OnTouchListener playListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				if (mpu.isPlaying()) {
					play_btn.setImageResource(R.drawable.playpress);
				} else {
					play_btn.setImageResource(R.drawable.pausepress);
				}
			}

			else if (event.getAction() == MotionEvent.ACTION_UP) {
				if (mpu.isPlaying()) {
					pause();
					play_btn.setImageResource(R.drawable.play);
				} else {
					play_btn.setImageResource(R.drawable.pause);
					current_music_name_text.setText("05 Daddy's eyes.mp3");// TO-DO
					play("/sdcard/05 Daddy's eyes.mp3");
					// /sdcard/05 Daddy's eyes.mp3
				}
			}
			return false;
		}

	};

	OnTouchListener prevListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				prev_btn.setImageResource(R.drawable.backwardpress);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				preMusicName();
				prev_btn.setImageResource(R.drawable.backward);
				previousOrNext(getMusicPath(selected_music_name));
				current_music_name_text.setText(selected_music_name);
				// /sdcard/05 Daddy's eyes.mp3
				play_btn.setImageResource(R.drawable.pause);
			}
			return false;
		}

	};

	OnTouchListener nextListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				next_btn.setImageResource(R.drawable.forwardpress);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				nextMusicName();
				next_btn.setImageResource(R.drawable.forward);
				current_music_name_text.setText(selected_music_name);
				previousOrNext(getMusicPath(selected_music_name));
				// /sdcard/05 Daddy's eyes.mp3
				play_btn.setImageResource(R.drawable.pause);

				// mpu.setDataSource("/sdcard/05 Daddy's eyes.mp3");// TO-DO
				// mpu.prepare();
				// /sdcard/05 Daddy's eyes.mp3
				play_btn.setImageResource(R.drawable.pause);

			}
			return false;
		}

	};

	OnTouchListener stopListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				stop_btn.setImageResource(R.drawable.stoppress);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				seek_bar_handler.removeCallbacks(refresh);
				stop();
				// mpu.stop();//TO-DO Research this.
				stop_btn.setImageResource(R.drawable.stop);
				play_btn.setImageResource(R.drawable.play);
			}
			return false;
		}

	};

	OnTouchListener backListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				back_btn.setImageResource(R.drawable.back_pressed);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				back_btn.setImageResource(R.drawable.back);
				removeDialog(MUSIC_LIST_DIALOG);
			}
			return false;
		}

	};

	OnTouchListener addMusicListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				Intent toDirectory = new Intent();
				toDirectory
						.setClass(MainActivity.this, DirectoryActivity.class);
				startActivityForResult(toDirectory,
						Constants.MAIN_TO_DIRECTORY_REQUEST_CODE);
			}
			return false;
		}

	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == Constants.MAIN_TO_DIRECTORY_REQUEST_CODE) {
			// Bundle bundle = data.getExtras();
			switch (resultCode) {
			case Constants.DIRECTORY_TO_MAIN_RESULT_CODE:
				// File file = (File) bundle.get("filePath");
				// if (null != file) {
				// /music_list.add(file.getName());
				music_list = getMusicList();
				play_list_view.setAdapter(new MusicAdapter(this, music_list));
				// }
				break;
			}
		}

	}

	// 调用showDialog(int id) 需要重写 onCreateDialog方法
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case MUSIC_LIST_DIALOG:
			LayoutInflater factory = LayoutInflater.from(this);
			View playListView = factory.inflate(R.layout.play_list_view, null);
			// this.getApplicationContext().getSystemService(LOCATION_SERVICE);
			// 1 public static LayoutInflater from(Context context) {
			// 2 LayoutInflater LayoutInflater =
			// 3 (LayoutInflater)
			// context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			// 4 if (LayoutInflater == null ) {
			// 5 throw new AssertionError( "LayoutInflater not found." );
			// 6 }
			// 7 return LayoutInflater;
			// 8 }
			play_list_view = (ListView) playListView
					.findViewById(R.id.play_list_view);
			play_list_view
					.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
						@Override
						public void onCreateContextMenu(ContextMenu menu,
								View v, ContextMenuInfo info) {
							menu.setHeaderTitle("Music Player");
							menu.add(0, 1, 0, "play")
									.setOnMenuItemClickListener(
											new OnMenuItemClickListener() {
												@Override
												public boolean onMenuItemClick(
														MenuItem item) {
													try {
														if (mpu.isPlaying()) {
															mpu.reset();
														}
														current_music_name_text
																.setText(selected_music_name);
														play(getMusicPath(selected_music_name));
													} catch (IllegalArgumentException e) {
														e.printStackTrace();
													} catch (IllegalStateException e) {
														e.printStackTrace();
													}
													return false;
												}
											});
							menu.add(0, 2, 6, "delete")
									.setOnMenuItemClickListener(
											new OnMenuItemClickListener() {
												@Override
												public boolean onMenuItemClick(
														MenuItem item) {
													return false;
												}
											});
						}
					});

			play_list_view.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View v, int arg2,
						long arg3) {
					// selected_list_id = arg3;
					selected_music_name = play_list_view
							.getItemAtPosition(arg2).toString();
					play_list_view.showContextMenu();
				}

			});
			music_list = getMusicList();
			play_list_view.setAdapter(new MusicAdapter(this, music_list));
			music_list_dialog = new AlertDialog.Builder(this).setIcon(
					R.drawable.music_file).setTitle("Music List").setView(
					playListView).create();
			back_btn = (ImageButton) playListView.findViewById(R.id.back_btn);
			back_btn.setOnTouchListener(backListener);
			add_music_btn = (ImageButton) playListView
					.findViewById(R.id.add_music_btn);
			add_music_btn.setOnTouchListener(addMusicListener);
			return music_list_dialog;
		}
		return null;
	}

	protected List<String> getMusicList() {
		List<String> musicList = new ArrayList<String>();
		ContentResolver cr = getContentResolver();
		Uri uri = DataBaseProvider.CONTENT_URI;
		String[] projection = { FileTable.NAME };
		Cursor c = cr.query(uri, projection, null, null, null);
		if (c.moveToFirst()) {
			for (int i = 0; i < c.getCount(); i++) {
				c.moveToPosition(i);
				musicList.add(c.getString(0));
			}
		}
		c.close();
		return musicList;
	}

	public String getMusicPath(String name) {
		ContentResolver cr = getContentResolver();
		Uri uri = DataBaseProvider.CONTENT_URI;
		String[] projection = { FileTable.PATH };
		String selection = FileTable.NAME + "=?";
		String[] selectionArgs = { name };
		Cursor c = cr.query(uri, projection, selection, selectionArgs, null);
		if (c.moveToFirst()) {
			String path = c.getString(0);
			return path;
		}
		c.close();
		return null;
	}

	public void preMusicName() {
		music_list = getMusicList();
		if (selected_music_name == null) {
			selected_music_name = music_list.get(0);
			return;
		}
		for (int i = 0; i < music_list.size(); i++) {
			if (music_list.get(i).equals(selected_music_name)) {
				if (i == 0) {
					selected_music_name = music_list.get(music_list.size() - 1);
					return;
				} else {
					selected_music_name = music_list.get(i - 1);
					return;
				}
			}
		}

	}

	public void nextMusicName() {
		music_list = getMusicList();
		if (selected_music_name == null) {
			selected_music_name = music_list.get(0);
			return;
		}
		for (int i = 0; i < music_list.size(); i++) {
			if (music_list.get(i).equals(selected_music_name)) {
				if (i == music_list.size() - 1) {
					selected_music_name = music_list.get(0);
					return;

				} else {
					selected_music_name = music_list.get(i + 1);
					return;

				}
			}
		}

	}

	private String getFileTime(int timeMs) {
		int totalSeconds = timeMs / 1000;// 获取文件有多少秒
		StringBuilder mFormatBuilder = new StringBuilder();
		Formatter mFormatter = new Formatter(mFormatBuilder, Locale
				.getDefault());
		int seconds = totalSeconds % 60;
		int minutes = (totalSeconds / 60) % 60;
		int hours = totalSeconds / 3600;
		mFormatBuilder.setLength(0);

		if (hours > 0) {
			return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds)
					.toString();// 格式化字符串
		} else {
			return mFormatter.format("%02d:%02d", minutes, seconds).toString();
		}
	}

	private Runnable refresh = new Runnable() {
		public void run() {
			int currently_Progress = seek_bar.getProgress() + 1000;// 加1秒
			seek_bar.setProgress(currently_Progress);
			current_time.setText(getFileTime(mpu.getCurrentPosition()));// 每1000m刷新歌曲音轨
			seek_bar_handler.postDelayed(refresh, 1000);
		}
	};

	private void play(String url) {
		if (mpu == null) {
			mpu = MediaPlayerUtil.getInstance(onCompeletionListener);
		}
		if (mpu.isPause()) {
			try {
				mpu.play();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			seek_bar_handler.postDelayed(refresh, 1000);
			return;
		} else {
			// isPlaying or isStop
			seek_bar_handler.removeCallbacks(refresh);
			mpu.reset();
			try {
				mpu.setDataSource(url);
				mpu.play();
				seek_bar.setMax(mpu.getDuration());
				seek_bar.setProgress(1);
				current_time.setText(getFileTime(mpu.getCurrentPosition()));
				end_time.setText(getFileTime(mpu.getDuration()));
				seek_bar_handler.postDelayed(refresh, 1000);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}

	}

	private void stop() {
		seek_bar_handler.removeCallbacks(refresh);
		if (mpu == null) {
			mpu = MediaPlayerUtil.getInstance(onCompeletionListener);
		}
		mpu.stop();
	};

	private void pause() {
		if (mpu == null) {
			mpu = MediaPlayerUtil.getInstance(onCompeletionListener);
		}
		seek_bar_handler.removeCallbacks(refresh);
		mpu.pause();
	}

	private void previousOrNext(String url) {
		seek_bar_handler.removeCallbacks(refresh);
		if (mpu == null) {
			mpu = MediaPlayerUtil.getInstance(onCompeletionListener);
		}
		mpu.reset();
		try {
			mpu.setDataSource(url);
			mpu.previousOrNext();
			seek_bar.setMax(mpu.getDuration());
			seek_bar.setProgress(1);
			current_time.setText(getFileTime(mpu.getCurrentPosition()));
			end_time.setText(getFileTime(mpu.getDuration()));
			seek_bar_handler.postDelayed(refresh, 1000);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}